package com.eportal.service.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;
import com.eportal.action.background.TKeysAction;
import com.eportal.dao.TKeysEntityMapper;
import com.eportal.dao.TLocksEntityMapper;
import com.eportal.dao.TUsersEntityMapper;
import com.eportal.domain.Sysopt;
import com.eportal.entity.TKeysEntity;
import com.eportal.entity.TLocksEntity;
import com.eportal.entity.TUsersEntity;
import com.eportal.params.background.TKeys.TKeyParam;
import com.eportal.service.*;
import com.eportal.util.CityUtil;
import com.eportal.vo.controller.background.tkeys.TKeyListVO;
import com.framework.jqgrid.PageEntity;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.eportal.aop.LogAnnotation;
import com.eportal.api.MdOpenApi;
import com.eportal.api.MdOpenQryKeysJson.Key;
import com.eportal.base.BaseDAO;
import com.eportal.domain.TKeys;
import com.eportal.domain.TLock;
import com.eportal.domain.TUsers;
import com.eportal.exception.MdKnownRunTimeException;
import com.eportal.exception.NotUniqueException;
import com.eportal.util.DateUtils;
import com.eportal.util.ValidateUtil;
import com.framework.jqgrid.JqGridPager;

@Service("tKeysService")
public class TKeysServiceImpl extends BaseServiceImpl<TKeysEntity> implements TKeysService{

	private Map<String, Object> result = new HashMap<String, Object>();
	private static Logger log = Logger.getLogger(TKeysServiceImpl.class.getName());

	@Autowired
	private TAgentService tAgentService;
	@Autowired
    private TLocksService tlocksService;
	@Resource(name="dao")
	private BaseDAO dao;

	@Resource
	private TKeysEntityMapper tKeyDao;

	@Resource
	private TUsersEntityMapper tUserDao;

	@Resource
	private TLocksEntityMapper tLockDao;



	public HttpSession getSession() {
        return ServletActionContext.getRequest().getSession();
    }
	@Override
	public TKeys get(Long sid){
		TKeys tKeys = (TKeys)dao.getById(TKeys.class, sid);
		return tKeys;
	}

	public TKeys getByWhere(String where){
		StringBuffer sb = new StringBuffer("from TKeys where ");
		sb.append(where);
		return (TKeys) dao.loadObject(sb.toString());
	}

	@Override
	public List<Map<String, Object>> list(String sql, JqGridPager jqGridPager) {
	     return dao.query(sql, jqGridPager);
	}
	@Override
	public int countSizeApp(String pageAppWhere) {
		int count = dao.count("select count(t.sid) from T06_KEYS t left join t03_community c on t.communityid=c.sid where " + pageAppWhere );
		return count;
	}
	@Override
	public List<Map<String, Object>> listPageApp(String where, int beginNum, int endNum,String type) {
		StringBuffer sql =new StringBuffer();
		sql.append("select b.* from "
					+ "(select rownum rb,a.* from "
						+ "(select rownum rn,t.sid,to_char(t.validity,'yyyy-mm-dd') as validity,t.pid,t.lock_name,t.status,u.auname,u.tel,t.communityid,c.agtcode "
						+ "from T06_KEYS t "
						+ "left join t03_community c on t.communityid=c.sid "
						+ "left join t04_users u on t.userid=u.userid "
						+ "where ");
						sql.append(where);
						sql.append(" )a ");
						sql.append(" where rn<= ");
						sql.append(endNum);
						sql.append(")");
					sql.append(" b where rb>");
					sql.append(beginNum);
		if("2".equals(type)){//到期时间最长
			sql.append(" order by validity desc");
		}
		if("3".equals(type)){//到期时间最短
			sql.append(" order by validity asc");
		}
		return dao.queryBySql(sql.toString());
	}
	@Override
	public void delete(Long id) {
		TKeys tKeys = (TKeys) dao.getById(TKeys.class, id);
        dao.delete(tKeys);
	}
	@Override
	public void update(TKeys tKeys) throws Exception {
        dao.update(tKeys);
	}

	@Override
	public void delete(List<Long> ids) {
		 for (Long id : ids) {
	            delete(id);
	     }
	}
	@Override
	public void add(TKeys tKeys) throws Exception {
		dao.save(tKeys);
	}


	public List<TKeys> listByTKeysHql(String hql) {
		return dao.query(hql);
	}

	@Override
	public TKeys getTKeys(String userId, String pid) {
		StringBuffer where  = new StringBuffer("userId ='");
	    where.append(userId);
	    where.append("' and pid='");
	    where.append(pid);
	    where.append("' order by sid desc");
	    TKeys tKeys = null;
	    String hql = "from TKeys where "+where.toString();
	    List<TKeys> listTKeys =  listByTKeysHql(hql);
	    if (listTKeys != null && listTKeys.size()>0) {
	    	tKeys = listTKeys.get(0);
	    }
	    return tKeys;
	}

	/**
	 * 获取手机开门钥匙
	 * @param userId
	 * @param pid
	 * @return
	 */
	private TKeys getAppOpenKeys(String userId, String pid) {
		StringBuffer where  = new StringBuffer("userId ='");
	    where.append(userId);
	    where.append("' and pid='");
	    where.append(pid+"'");
	    where.append(" and (opentype='2' or opentype is null)");
	    where.append(" order by sid desc");
	    TKeys tKeys = null;
	    String hql = "from TKeys where "+where.toString();
	    List<TKeys> listTKeys =  listByTKeysHql(hql);
	    if (listTKeys != null && listTKeys.size()>0) {
	    	tKeys = listTKeys.get(0);
	    }
	    return tKeys;
	}



	/**
     * 钥匙新增保存
     */
    @LogAnnotation(operateDescribe="钥匙新增")
    public Map<String, Object> addMethod(TKeys tKey) {
    	String msg = ValidateUtil.validate(tKey);
        if (msg == null || msg.trim().length() == 0) {
	    	try {
	    		tKey.setReqTime(new Timestamp(System.currentTimeMillis()));
	    		add(tKey);
	    		result.put("objectId", tKey.getSid());
	    		result.put("code", 1);
	            result.put("msg", "操作成功");
	        } catch (Exception e) {
	            log.error("钥匙新增保存失败", e);
	            result.put("code", 0);
	            result.put("msg", "操作失败");
	        }
        } else {
            result.put("code", 0);
            result.put("msg", msg);
        }
        return result;
    }

	/**
     * 钥匙修改保存
     */
    @LogAnnotation(operateDescribe="钥匙修改")
    public Map<String, Object> updateMethod(TKeys tKeys){
    	 String msg = ValidateUtil.validate(tKeys);
    	 result.put("objectId", tKeys.getSid());
         if (msg == null || msg.trim().length() == 0) {
             try {
            	TKeys entity = get(tKeys.getSid());
             	entity.setValidity(tKeys.getValidity());
             	entity.setPid(tKeys.getPid());
             	entity.setAlgorithmVer(tKeys.getAlgorithmVer());
             	entity.setLockName(tKeys.getLockName());
            	update(entity);
                result.put("code", 1);
                result.put("msg", "操作成功");
             } catch (Exception e) {
                 log.error("钥匙更新失败", e);
                 result.put("code", 0);
                 result.put("msg", "操作失败");
             }
         } else {
             result.put("code", 0);
             result.put("msg", msg);
         }
         return result;
    }

	/**
     * 删除
     */
    @LogAnnotation(operateDescribe="钥匙删除")
    public Map<String, Object> deleteMethod(String param_ids) {
    	 try {
    		 result.put("objectId", param_ids);
             List<Long> ids = new LinkedList<Long>();
             for (String s : param_ids.split(",")) {
                 ids.add(Long.parseLong(s));
             }
             delete(ids);
             result.put("code", 1);
             result.put("msg", "操作成功");
         } catch (Exception e) {
             log.error("钥匙删除失败", e);
             result.put("code", 0);
             result.put("msg", "操作失败");
         }
    	 return result;
    }

	@Override
	@LogAnnotation(operateDescribe="用户钥匙修改操作")
	public Map<String, Object> changeKeysStatusMethod(String sid, String status, String validity,TUsers tUser) {
		 try {
			 result.put("objectId", sid);
			 TKeys tKeys = get(Long.parseLong(sid));
			 if (StringUtils.isNotBlank(status)) {
				 tKeys.setStatus(status);
			 }
			 if (StringUtils.isNotBlank(validity)) {
				 //重新申请钥匙
				 StringBuffer where =  new StringBuffer();
				 where.append(" and pid='");
				 where.append(tKeys.getPid());
				 where.append("'");
				 List<TLock> list = tlocksService.getBySql(where.toString());
				 result = SyncTo(tUser,list,validity,tUser.getAgtCode(),null);
			 }
			 update(tKeys);
             result.put("code", 1);
             result.put("msg", "操作成功");
         } catch (Exception e) {
             log.error("钥匙状态修改失败", e);
             result.put("code", 0);
             result.put("msg", "钥匙状态修改失败");
         }
    	 return result;
	}

	/**
	 * @param validityDate
	 * @param communityId
	 * @param installunitId
	 * @Description: 请求钥匙
	 * @param entity
	 * @return
	 */
	public Map<String, Object> SyncTo ( TUsers tUser, List<TLock> lockList, String validityDate, String agtCode,Date startTime){

		return syncTo(tUser, lockList, validityDate, agtCode, null,startTime);
	}

	/**
	 *
	 * @param tUser
	 * @param lockList
	 * @param apiValidityDate 向开放平台申请钥匙的有效期
	 * @param agtCode
	 * @param localValidDate 本地数据库存储的有效期
	 * @return
	 */

	public Map<String, Object> syncTo ( TUsers tUser, List<TLock> lockList, String apiValidityDate, String agtCode,Date localValidDate,Date startTime){
		List pidList = new ArrayList<>();
		for(TLock bean:lockList){
			pidList.add(bean.getPid());
		}

		return syncTo(tUser.getUserId(), tUser.getTel(), pidList, DateUtils.stringToDate(apiValidityDate, "yyyy-MM-dd"), agtCode, localValidDate, startTime);
	}

	/*public Map<String, Object> syncTo ( TUsers tUser, List<TLock> lockList, String apiValidityDate, String agtCode,Date localValidDate,Date startTime){
		try {

			if(localValidDate==null){
				//localValidDate = DateUtils.stringToDate(apiValidityDate+" 23:59:59", "yyyy-MM-dd HH:mm:ss");
				localValidDate = DateUtils.stringToDate(apiValidityDate+" 00:00:00", "yyyy-MM-dd HH:mm:ss");//update by wangk
			}
			if(startTime==null){//钥匙的开始有效时间
				startTime = new Date();
			}



			String pid = "";
			for (int i = 0; i < lockList.size(); i++) {
                TKeys tKeys = getTKeys(tUser.getUserId(),lockList.get(i).getPid());
		        if (tKeys != null && tKeys.getValidity() != null) {
		        	String validity = DateUtils.dateFormat1.format(tKeys.getValidity());
		        	if (tKeys !=null && apiValidityDate.replaceAll("-", "").equals(validity)) {//原来有效期相同会跳过，考虑到
		        		//continue;
		        	}
				}
				//拼接pid字符串
				if (pid != "") {
					pid +=",";
				}
				pid +=lockList.get(i).getPid();
				//放入pid对应的安装点
//				result.put(lockList.get(i).getPid(), lockList.get(i).getInstallunitId());
			}
	       if(pid == ""){
	    	   result.put("code", 1);
     	       result.put("msg", "操作成功");
     	       return result;
	       }
			Map<String,String> map = tAgentService.getPlatAppKey(agtCode);

			String validApi="";

			Map<String, Object> resultMap = MdOpenApi.qeyKeys(pid,map.get("agt_num"),map.get("app_key"),tUser.getTel(),apiValidityDate.replaceAll("-", ""));
			if ("0".equals(resultMap.get("code").toString())) {
				List<Key> list = (List<Key>) resultMap.get("list");
					if(list.size()>0){
						for (int i = 0; i < list.size(); i++) {
			                TKeys tKeys = getTKeys(tUser.getUserId(),list.get(i).getPid());
			                boolean bool = false;
			                if (tKeys !=null) {
			                	bool = true;//修改
							}else{
								tKeys = new TKeys();
							}
//			                String installunitId = (String) result.get(list.get(i).getPid());
							tKeys.setKeyContent(list.get(i).getLock_id());
							StringBuffer sb = new StringBuffer();
			                sb.append(" pid='");
			                sb.append(list.get(i).getPid());
			                sb.append("'");
			                TLock tlock = tlocksService.getHql(sb.toString());
			                tKeys.setInstallunitId(tlock.getInstallunitId());
			                tKeys.setLockName(tlock.getInstallLockName());
			                tKeys.setKeyContent(list.get(i).getLock_id());
							tKeys.setPlatDepartid(list.get(i).getCommunity());
							tKeys.setReqTime(new Timestamp(System.currentTimeMillis()));
							tKeys.setValidity(new Timestamp(localValidDate.getTime()));
							tKeys.setAlgorithmVer(list.get(i).getAlgorithmVer());
							tKeys.setPlatKeyId(list.get(i).getKsid());
							tKeys.setStatus("0");
							tKeys.setCommunityId(lockList.get(0).getCommunityId());
							tKeys.setStartTime(new Timestamp(startTime.getTime()));
			                if (bool) {
					        	update(tKeys);
							}else{
								tKeys.setPid(list.get(i).getPid());
								tKeys.setUserId(tUser.getUserId());
								add(tKeys);
							}

						}
						result.put("code", 1);
						result.put("msg", "操作成功");
				}
			}else{
				log.error("钥匙申请失败，resultMap:"+resultMap);
				result.put("code", 2);
      	        result.put("msg", resultMap.get("msg"));
			}
    	} catch (Exception e) {
    		log.error("钥匙申请失败", e);
    		result.put("code", 0);
  	        result.put("msg", "钥匙申请失败");
  	        throw new MdKnownRunTimeException("钥匙申请失败");
    	}
		return result;
	}*/

	public  Map<String, Object> syncTo ( String userid,String tel,List<String> pidList,  Date apiValidityDate, String agtCode,Date localValidDate,Date startTime){
		try {
			if(localValidDate==null){
				//localValidDate = DateUtils.stringToDate(apiValidityDate+" 23:59:59", "yyyy-MM-dd HH:mm:ss");
				localValidDate = DateUtils.stringToDate(DateUtils.formatDate(apiValidityDate)+" 00:00:00", "yyyy-MM-dd HH:mm:ss");//update by wangk
			}
			//TODO wangk 2017-7-26 22:31:10
			apiValidityDate = DateUtils.addDay(localValidDate, 1);

			if(startTime==null){//钥匙的开始有效时间
				startTime = new Date();
			}
			String pid = "";
			for (int i = 0; i < pidList.size(); i++) {
				//原来有效期相同会跳
	          /*  TKeys tKeys = getTKeys(userid,pidList.get(i));
		        if (tKeys != null && tKeys.getValidity() != null) {
		        	String validity = DateUtils.dateFormat1.format(tKeys.getValidity());
		        	if (tKeys !=null && DateUtils.formatDatetime(apiValidityDate, "yyyymMMdd").equals(validity)) {
		        		//continue;
		        	}
				}*/
				//拼接pid字符串
				if (pid != "") {
					pid +=",";
				}
				pid +=pidList.get(i);
				//放入pid对应的安装点
//				result.put(lockList.get(i).getPid(), lockList.get(i).getInstallunitId());
			}
	       if(pid == ""){
	    	   result.put("code", 1);
	 	       result.put("msg", "操作成功");
	 	       return result;
	       }
			Map<String,String> map = tAgentService.getPlatAppKey(agtCode);

			String validApi="";

			Map<String, Object> resultMap = MdOpenApi.qeyKeys(pid,map.get("agt_num"),map.get("app_key"),tel,DateUtils.formatDatetime(apiValidityDate, "yyyyMMdd"));

			if ("0".equals(resultMap.get("code").toString())) {
				List<Key> list = (List<Key>) resultMap.get("list");
					if(list.size()>0){
						for (int i = 0; i < list.size(); i++) {
			                TKeys tKeys = getAppOpenKeys(userid,list.get(i).getPid());
			                boolean bool = false;
			                if (tKeys !=null) {
			                	bool = true;//修改
							}else{
								tKeys = new TKeys();
							}
//			                String installunitId = (String) result.get(list.get(i).getPid());
							tKeys.setKeyContent(list.get(i).getLock_id());
							StringBuffer sb = new StringBuffer();
			                sb.append(" pid='");
			                sb.append(list.get(i).getPid());
			                sb.append("'");
			                TLock tlock = tlocksService.getHql(sb.toString());
			                tKeys.setInstallunitId(tlock.getInstallunitId());
			                tKeys.setLockName(tlock.getInstallLockName());
			                tKeys.setKeyContent(list.get(i).getLock_id());
							tKeys.setPlatDepartid(list.get(i).getCommunity());
							tKeys.setReqTime(new Timestamp(System.currentTimeMillis()));
							tKeys.setValidity(new Timestamp(localValidDate.getTime()));
							tKeys.setAlgorithmVer(list.get(i).getAlgorithmVer());
							tKeys.setPlatKeyId(list.get(i).getKsid());
							tKeys.setStatus("0");
							tKeys.setCommunityId(tlock.getCommunityId());
							tKeys.setStartTime(new Timestamp(startTime.getTime()));
			                if (bool) {
					        	update(tKeys);
							}else{
								tKeys.setPid(list.get(i).getPid());
								tKeys.setUserId(userid);
								add(tKeys);
							}

						}
						result.put("code", 1);
						result.put("msg", "操作成功");
				}
			}else{
				log.error("钥匙申请失败，resultMap:"+resultMap);
				result.put("code", 2);
	  	        result.put("msg", resultMap.get("msg"));
			}
		}catch (Exception e) {
    		log.error("钥匙申请失败", e);
    		result.put("code", 0);
  	        result.put("msg", "钥匙申请失败");
  	        throw new MdKnownRunTimeException("钥匙申请失败");
    	}
		return result;




	}

	public Map<String, Object> syncTo ( String userid,String tel,String pid, Date apiValidityDate, String agtCode,Date localValidDate,Date startTime){
		List pidList = new ArrayList<>();
		pidList.add(pid);
		return syncTo(userid, tel, pidList, apiValidityDate, agtCode, localValidDate, startTime);
	}


	/**
	 * 硬件更换，在硬件损坏等情况下，社区可以更换设备
	 * @param sid
	 * @param newSid
	 * @param communityid
	 * @param installer
	 * @param sysopt			当前用户
	 * @throws Exception
	 */

	@Override
	public void change(String sid, String newSid, String communityid,Long installer,Sysopt sysopt) throws Exception {
		TLock lock = tlocksService.get(Long.valueOf(sid));
		TLock newLock = tlocksService.get(Long.valueOf(newSid));
			if("1".equals(lock.getStatus())){
				newLock.setInstallLockName(lock.getInstallLockName());
				newLock.setCommunityId(lock.getCommunityId());
				newLock.setInstallLockName(lock.getInstallLockName());
				newLock.setAgtCode(lock.getAgtCode());
				Map map = tlocksService.SyncTo(newLock,sysopt); //todo Updated by Saber on 2017/7/27 上午11:13
				if(new Integer(1).equals(map.get("code"))){
					String hql="from TKeys where status='0' and validity>=to_date('"+DateUtils.currentDatetime()+"'"+",'yyyy-mm-dd HH24:mi:ss') and pid='"+lock.getPid()+"' and communityId='"+communityid+"' order by sid";
					int pageSize=1000;
					int i=1;
					int size = 1;
					List lockList = new ArrayList();
					lockList.add(newLock);
					while(size>0){
						List<TKeys> list = dao.query(hql, i, pageSize);
						for(TKeys bean:list){
							TUsers user;
							try {
								user = (TUsers)dao.getUniqueFirst("from TUsers where userid='"+bean.getUserId()+"'");
							} catch (NotUniqueException e) {
								log.error(this, e);
								throw new Exception(e.getMessage());
							}
							Map tkeyMap = SyncTo(user, lockList, DateUtils.formatDatetime(new Date(bean.getValidity().getTime()), "yyyy-MM-dd"),lock.getAgtCode(),null);
							if("1".equals(tkeyMap.get("code").toString())){
								bean.setStatus("1");//老钥匙设置失效
								dao.update(bean);
							}else{
								log.info("key.sid="+bean.getSid()+",");
								throw new MdKnownRunTimeException("申请钥匙失败");
							}

						}
						size = list.size();
						i++;
					}
					newLock.setStatus("1");//新设备变成已安装状态
					newLock.setInstallunitId(lock.getInstallunitId());
					newLock.setIsPubUnit(lock.getIsPubUnit());
					newLock.setInstallTime(new Timestamp(new Date().getTime()));
					newLock.setInstallWork(String.valueOf(installer));
					dao.update(newLock);
					lock.setStatus("0");//老设备变成未安装状态
					lock.setInstallTime(null);
					lock.setInstallunitId(null);
					lock.setInstallLockName(null);
					lock.setInstallWork(null);
					dao.update(lock);
					dao.excute("update TMIRROR_KEYS set status='1' where pid='"+lock.getPid()+"'");//将老访客钥匙失效
				}else{
					throw new MdKnownRunTimeException("安装设备失败");
				}
			}else{
				throw new MdKnownRunTimeException("操作失败，原设备信息不符");
			}

	}
	@Override
	public List page4Prolong(String agtCode, String communityId, String next_sid) {
		// TODO Auto-generated method stub
		String sql="select a.*,b.tel,b.auname,c.install_lock_name from t06_keys_prolong a,t04_users b,t05_locks c where a.apply_userid=b.userid and a.pid=c.pid and a.communityid='"+communityId+"'";
		if(next_sid!=null && next_sid.length()>0){
			sql +=" and sid<"+next_sid;
		}
		sql +=" order by a.sid desc";
		return dao.queryBySql(sql);

	}


//todo -----------------------------------------------------------------------------------------------

	/**
	 * 同步
	 *
	 * @param tUsersEntity TUsersEntity 对象
	 * @param list         TLocksEntity list
	 * @param validityDate 向开放平台申请钥匙的有效期
	 * @param agtCode      合作方编码
	 * @param startTime    本地数据库存储的有效期
	 * @return
	 * @author Saber
	 * @Date 2017/8/14 上午9:17
	 * @see TKeysServiceImpl#SyncTo(TUsers, List, String, String, Date)
	 */
	@Override
	public JSONObject SyncTo(TUsersEntity tUsersEntity, List<TLocksEntity> list, String validityDate, String agtCode, Date startTime) {
		return syncTo(tUsersEntity,list,validityDate,agtCode,null,startTime);
	}

	/**
	 * 钥匙同步
	 *
	 * @param tUsersEntityr   TUsersEntity 对象
	 * @param lockList        TLocksEntity list
	 * @param apiValidityDate 向开放平台申请钥匙的有效期
	 * @param agtCode         合作方编码
	 * @param localValidDate  本地数据库存储的有效期
	 * @param startTime       钥匙的开始有效时间
	 * @return
	 * @author Saber
	 * @Date 2017/8/14 上午9:29
	 * @see TKeysServiceImpl#syncTo(TUsers, List, String, String, Date, Date)
	 */
	@Override
	public JSONObject syncTo(TUsersEntity tUsersEntityr, List<TLocksEntity> lockList, String apiValidityDate, String agtCode, Date localValidDate, Date startTime) {

		List pidList = new ArrayList<>();
		for(TLocksEntity bean:lockList){
			pidList.add(bean.getPid());
		}

		JSONObject json = new JSONObject();
		Map<String,Object> map=syncTo(tUsersEntityr.getUserid(), tUsersEntityr.getTel(), pidList, DateUtils.stringToDate(apiValidityDate, "yyyy-MM-dd"), agtCode, localValidDate, startTime);
		json.putAll(map);
		return json;
	}

	/**
	 * 钥匙管理列表接口
	 *
	 * @param pageEntity 分页对象
	 * @param param      查询参数
	 * @param user       当前用户
	 * @param userRole   当前用户userRole
	 * @return
	 * @author Saber
	 * @Date 2017/8/14 上午11:18
	 * @see TKeysAction#page()
	 */
	@Override
	public PageInfo<TKeyListVO> queryForPage(PageEntity pageEntity, TKeyParam param, Sysopt user, int userRole) {
		//执行分页
		PageHelper.startPage(pageEntity.getPageNo(), pageEntity.getPageSize());
		//排序
		String orderField = pageEntity.getSort();
		String orderDirection = pageEntity.getOrder();
		if (org.apache.commons.lang3.StringUtils.isNotEmpty(orderField)) {
			PageHelper.orderBy(orderField);
			if (org.apache.commons.lang3.StringUtils.isNotEmpty(orderDirection)) {
				PageHelper.orderBy(orderField + " " + orderDirection);
			}
		}
		//判断是否是直辖市
		boolean isMunicipalities = false;
		if (org.apache.commons.lang3.StringUtils.isNotBlank(param.getAreaCode())) {
			isMunicipalities = CityUtil.isMunicipalities(param.getAreaCode());
		}

		List<TKeyListVO> list = tKeyDao.queryForList(param,isMunicipalities,user,userRole);
		return new PageInfo<>(list);
	}

	/**
	 * 修改钥匙状态或有效期
	 *
	 * @param sId      sId
	 * @param status   状态		默认,0正常，1停用,2:设备被回收（永久禁用）
	 * @param validity 有效期
	 * @param user     当前用户
	 * @param userRole 当前用户userRole
	 * @return
	 * @author Saber
	 * @Date 2017/8/14 下午6:02
	 * @see TKeysServiceImpl#changeKeysStatusMethod(String, String, String, TUsers)
	 */
	@Override
	public JSONObject changeKeys(Long sId, String status, String validity, Sysopt user, int userRole) {

		JSONObject json = new JSONObject();

		try {
			json.put("data", sId);

			if(sId == null){
				json.put("code",0);
				json.put("msg","唯一标识符必传");
				return json;
			}

			TKeysEntity tKeysEntity = tKeyDao.selectByPrimaryKey(sId);
			if(tKeysEntity==null){
				json.put("code",0);
				json.put("msg","钥匙不存在");
				return json;
			}
			if (StringUtils.isNotBlank(status)) {
				tKeysEntity.setStatus(status);
			}

			if (StringUtils.isNotBlank(validity)) {
				//重新申请钥匙
				TLocksEntity tLocksEntity = tLockDao.getByPid(tKeysEntity.getPid());
				List<TLocksEntity> list = new ArrayList<>();
				list.add(tLocksEntity);

				TUsersEntity tUser = tUserDao.getByUserId(tKeysEntity.getUserid());

				json = SyncTo(tUser,list,validity,tUser.getAgtcode(),null);
			}
			tKeyDao.updateByPrimaryKeySelective(tKeysEntity);
			json.put("code", 1);
			json.put("msg", "操作成功");
			return json;
		} catch (Exception e) {
			log.error("钥匙状态修改失败", e);
			json.put("code", 0);
			json.put("msg", "钥匙状态修改失败");
			return json;
		}
	}
}
